package com.runfast.waimai.web.controller.Runfastbusinesscontroller;

import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.RunfastBusinessService;
import com.runfast.waimai.service.RunfastGoodsSellRecordService;
import com.runfast.waimai.service.RunfastWithdrawService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 商家提现转账
 */
@Slf4j
@RestController
@RequestMapping("/server/business")
public class BusinessTakeMoneyController {

    @Autowired
    private RunfastWithdrawService rs;
    @Autowired
    private RunfastBusinessService rb;
    @Autowired
    private RunfastGoodsSellRecordService rg;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
    private SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
    private ExportExcel ex;

    @RequestMapping("/export")
    public Result export(HttpServletResponse response, @RequestParam(value="createtime1",required=false)String createtime1, @RequestParam(value="createtime2",required=false)String createtime2) {
        //System.out.println(createtime1+"----------------"+createtime2);
        if(createtime1==null || createtime2==null)
            return Result.fail(null,"请选择时间");
        try{
            OutputStream out = response.getOutputStream();
            Result result = count(createtime1, createtime2);
            if(result.isSuccess()){
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/vnd.ms-excel");
                String fileName = new String((sdf3.parse(createtime1)+"至"+sdf3.parse(createtime2)+"商家提现记录_"+ String.valueOf(System.currentTimeMillis())).getBytes(),"iso-8859-1");
                response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xls");//URLEncoder.encode(fileName, "utf-8")
                ex.export(out);
                return result;
            }else
                return result;
        } catch(Exception e){
            e.printStackTrace();
            return Result.fail(null,"导出失败");
        }
    }

    public Result count(String createtime1, String createtime2){
        log.info("------------------开始进行判断导出-----------------");
        List<RunfastWithdraw> rfwList = new ArrayList<RunfastWithdraw>();
        RunfastWithdrawExample rfwExample = new RunfastWithdrawExample();
        RunfastWithdrawExample.Criteria criteria = rfwExample.createCriteria();
        criteria.andAccountIsNotNull();
        criteria.andMonetaryGreaterThan(BigDecimal.ZERO);
        criteria.andApplytypeEqualTo(3);
        criteria.andStatusNotEqualTo(2);
        try {
            //System.out.println(sdf3.parse(createtime1)+"-----------"+sdf3.parse(createtime2));
            criteria.andCreatetimeBetween(sdf3.parse(createtime1),sdf3.parse(createtime2));//按照时间赛选     //getTwoDaysAgo(), getToday()查前一天的提现申请记录
        } catch (ParseException e1) {
            e1.printStackTrace();
            return Result.fail(null,"时间格式错误");
        }
        rfwList = rs.selectByExample(rfwExample);//.testData();
        //System.out.println("aaaaaaaaaaaaaaaaaaaaaa");

        if(rfwList!=null && !rfwList.isEmpty()){
            //拼装Excel数据
            String title = "商家提现统计记录";
            //String[] rowsName = new String[] { "序号", "客户名称", "客户电话", "提现类型", "银行类型", "提现账号", "提现金额", "申请时间" };
            String[] rowsName = new String[] { "业务参考号", "收款人编号", "收款人帐号", "收款人名称", "收方开户支行", "收款人所在省", "收款人所在市", "收方邮件地址", "收方移动电话", "币种", "付款分行", "结算方式", "业务种类", "付方帐号", "期望日", "期望时间", "用途", "金额", "收方行号", "收方开户银行", "业务摘要" };

            List<Object[]> dataList = new ArrayList<Object[]>();
            try {
                for(int i = 0; i < rfwList.size(); i++){
                    RunfastWithdraw recode = rfwList.get(i);
                    System.out.println(recode.getAccount()+"---------"+recode.getMonetary().floatValue()+"---------"+recode.getApplytype()+"---------"+recode.getStatus());
                    if(recode.getAccount()!=null && recode.getMonetary().floatValue()>0 && recode.getApplytype()==3 && recode.getStatus()!=2 && Calculation(recode.getMonetary(), recode.getWdate(),recode.getUserid() )) { //判断账户是否为空，金额是否大于0，是否是商家（代码3）提现，状态除了不通过（2），提现金额是否 符合通过
                        //导出EXcel
                        System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbbb");
                        Object[] objs = null;
                        objs = new Object[rowsName.length];

                        RunfastBusinessExample rfbExample = new RunfastBusinessExample();
                        rfbExample.createCriteria().andIdEqualTo(recode.getUserid());
                        RunfastBusiness business = rb.selectByPrimaryKey(recode.getUserid());
                        if(business!=null){
                            objs[1] = business.getId()!=null?recode.getId():" ";//收款人编号
                            objs[4] = (business.getEstablishbank()!=null)&&(!business.getEstablishbank().trim().equals(""))?business.getEstablishbank():" ";//收方开户支行
                            objs[5] = " ";//收款人所在省
                            objs[6] = (business.getCityname()!=null)&&(!business.getCityname().trim().equals(""))?business.getCityname():" ";//收款人所在市
                            objs[16] = ((business.getName()!=null)&&(!business.getName().trim().equals(""))?business.getName():" ")+"商家提现";
                            /*System.err.println("记录："+recode.getUsermobile()+"---商家："+business.getMobile());
                            System.err.println("记录："+recode.getAccount()+"---商家："+business.getAccount());
                            System.err.println("记录："+recode.getBanktype()+"---商家："+business.getBank()+"---商家开户行："+business.getEstablishbank());
                            System.err.println("记录："+recode.getName()+"---商家："+business.getEstablishname());
                            System.err.println("申请时间："+sdf.format(recode.getCreatetime()));*/
                        }
                        objs[0] = i+1;
                        objs[2] = (recode.getAccount()!=null)&&(!recode.getAccount().trim().equals(""))?recode.getAccount():" ";
                        objs[3] = (recode.getName()!=null)&&(!recode.getName().trim().equals(""))?recode.getName():" ";
                        objs[7] = " ";//收方邮件地址
                        objs[8] = (recode.getUsermobile()!=null)&&(!recode.getUsermobile().trim().equals(""))?recode.getUsermobile():" ";
                        objs[9] = "人民币";
                        objs[10] = "深圳";
                        objs[11] = "快速";
                        objs[12] = "普通汇兑";
                        objs[13] = "987654321012";
                        objs[14] = sdf2.format(getADayLater(new Date()));
                        objs[15] = "080000";
                        objs[20] = "商家提款自动打款";
                        objs[17] = recode.getMonetary()!=null?recode.getMonetary():" ";
                        objs[18] = " ";//行号
                        objs[19] = (recode.getBanktype()!=null)&&(!recode.getBanktype().trim().equals(""))?recode.getBanktype():" ";
                        dataList.add(objs);
                        //将匹配的记录状态state改为2(打款中)
                        /*RunfastWithdraw runfastWithdraw = new RunfastWithdraw();
                        runfastWithdraw.setId(recode.getId());
                        runfastWithdraw.setState(2);
                        rs.updateByPrimaryKeySelective(runfastWithdraw);*/
                        //转账操作
                        //将结果返回给商户
                        //修改状态，添加转账记录
                    }else {
                        //将不匹配的记录状态改为2(不通过)
                        /*RunfastWithdraw runfastWithdraw = new RunfastWithdraw();
                        runfastWithdraw.setId(recode.getId());
                        runfastWithdraw.setStatus(2);
                        rs.updateByPrimaryKeySelective(runfastWithdraw);*/
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
                log.info("导出失败！");
                return Result.fail(null,"导出失败");
            }
            try {
                if(dataList.isEmpty())
                    return Result.fail(null,"没有匹配的数据");
                ex = new ExportExcel(title, rowsName, dataList);
                log.info("导出成功！");
                return Result.ok("");
            } catch (Exception e) {
                e.printStackTrace();
                log.info("导出失败！");
                return Result.fail(null,"导出失败");
            }
        }else{
            return Result.fail(null,"没有匹配的数据");
        }

    }

    /**
     *
     * @param takeMoney 提现金额
     * @param businessId 商户ID
     * @param dateSpan 提现时间跨度
     * @return 提现金额通过：true
     * @throws ParseException
     */
    public boolean Calculation(BigDecimal takeMoney, String dateSpan, int businessId) throws ParseException{
        System.out.println(takeMoney.floatValue()+"----------------------"+dateSpan+"----------------"+businessId);
        List<RunfastGoodsSellRecord> recordList = null;
        if(dateSpan!=null){
            //根据Wdate字段截取提现跨度
            String dateBegin = dateSpan.substring(5, 15);
            String dateEnd = dateSpan.substring(17, 27);
            Date dateBeginD = getTheDayBegin(sdf3.parse(dateBegin));
            Date dateEndD = getTheDayEnd(sdf3.parse(dateEnd));
            RunfastGoodsSellRecordExample sellExample = new RunfastGoodsSellRecordExample();
            sellExample.createCriteria().andReadytimeBetween(dateBeginD, dateEndD).andBusinessidEqualTo(businessId);
            System.out.println(dateBeginD+"------------"+dateEndD+"-------------"+businessId);
            recordList = rg.selectByExample(sellExample);
        }
        BigDecimal totleAmount = BigDecimal.ZERO;
        if(recordList!=null && !recordList.isEmpty()){
            for(RunfastGoodsSellRecord list:recordList){
                totleAmount = totleAmount.add( list.getBusinesspay().subtract(list.getBusinessget()) );
            }
            System.out.println(takeMoney.floatValue()+"----------------------"+totleAmount);
            if(takeMoney.floatValue() == 0 || totleAmount.compareTo(takeMoney) != 0)
                return false;
            else
                return true;
        }else{
            return false;
        }
    }
    public Date getTwoDaysAgo() throws ParseException{
        Date date=sdf3.parse("2017-07-30");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -2);
        calendar.set(Calendar.HOUR, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        date = calendar.getTime();
        return date;
    }
    public Date getToday() throws ParseException{
        Date date=sdf3.parse("2017-07-30");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        date = calendar.getTime();
        return date;
    }
    public Date getTheDayBegin(Date date) throws ParseException{
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        date = calendar.getTime();
        return date;
    }
    public Date getTheDayEnd(Date date) throws ParseException{
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        date = calendar.getTime();
        return date;
    }
    public Date getADayLater(Date date) throws ParseException{
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +1);
        date = calendar.getTime();
        return date;
    }
}
